// Vue Router
const router = new VueRouter({
  mode: 'history',
  routes: [
    { path: '/', component: { template: '<div>Home</div>' } },
    { path: '/index', component: { template: document.getElementById('index-template').innerHTML } },
    { path: '/register', component: { template: document.getElementById('register-template').innerHTML } },
    { path: '/chat', component: { template: document.getElementById('chat-template').innerHTML }, meta: { requiresAuth: true } },
    { path: '/login', component: { template: document.getElementById('login-template').innerHTML } }
  ]
})

// Authentication state with localStorage persistence
const auth = {
  isAuthenticated: localStorage.getItem('isAuthenticated') === 'true',
  login() {
    this.isAuthenticated = true
    localStorage.setItem('isAuthenticated', true)
  },
  logout() {
    this.isAuthenticated = false
    localStorage.setItem('isAuthenticated', false)
  }
}

// Route guard
router.beforeEach((to, from, next) => {
  // Skip auth check for index and register routes
  if (to.path === '/index.html' || to.path === '/register') {
    return next()
  }

  // Check auth for protected routes
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!auth.isAuthenticated) {
      next({
        path: '/index.html',
        query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    next()
  }
})

new Vue({
  el: '#app',
  router,
  data: {
    auth: auth
  }
})